package com.urchin.avatarhero.util;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.widget.Toast;

import com.urchin.avatarhero.Prefs;
import com.urchin.avatarhero.util.cal.CalBlob;
import com.urchin.avatarhero.util.cal.CalendarHandler;

/**********************************************************************
AvatarHero - A task management RPG Android Application
Copyright (C) 2013  Peter Clay

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
***********************************************************************/

public class Utilities {
	Activity act;
	
	static String[] daysofweek = new String[] {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
	
	public Utilities(Activity a) {
		act = a;
	}
	
	public String convertToStrPattern(CalBlob cdata, String pattern) {
		String rstr = "";

		if(pattern.equals("caldisp")) {			// Based of the array of strings stored by BuildCalData
			// Get the database
			SQLiteHandler dbHandler = new SQLiteHandler(act.getApplicationContext());
			dbHandler.opendb();
			 
			rstr = this.convertToStrPattern(cdata, pattern, dbHandler);

			dbHandler.closedb();
		}
		
		return rstr;
	}
	
	// This method MUST have the database opened by the calling class
	public String convertToStrPattern(CalBlob cdata, String pattern, SQLiteHandler handler) {
		String rstr = "";
		String ampm = "";
		int diff = 0;
		
		// Set Calendar Stuff
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(cdata.getStarttime());
		String estrdate = CalendarHandler.dformatter.format(cal.getTime());
				
		if(pattern.equals("caldisp")) {			// Based of the array of strings stored by BuildCalData
			// Extract the difficulty from the database			
			Cursor rcursor = handler.getQuest(cdata.getCalid(), cdata.getEventid(), cdata.getInstanceid());		// Get the quest data (If it exists)
			
			if(rcursor.getCount() == 1) {		// Has been assigned as a quest
				if(rcursor.moveToFirst()) {
					diff = rcursor.getInt(3);			// Difficulty	
				}
			} else {							// Show as difficulty 0
				diff = 0;
			}
			rcursor.close();		
				 
			rstr = cdata.getTitle() + "\n" + daysofweek[cal.get(Calendar.DAY_OF_WEEK) - 1] + ", " + estrdate + " | " + "Lvl: " + String.valueOf(diff);
		}
		
		return rstr;
	}
	
	// Return a calendar blob object of the parsed string
	public CalBlob StrPatternToCalBlob(String str) {
		CalBlob cb = new CalBlob();
		Date chosendate = null;
		
		 String[] calstuff = str.split("[\n|,]");		// Will contain name, date, diff
		 
		 // Get the Event and Instance data
		 try {
			 StringBuilder sb = new StringBuilder(calstuff[2].trim());
			 chosendate = CalendarHandler.dformatter.parse(sb.toString());
		 } catch (ParseException e) {
			 e.printStackTrace();
			 throw new RuntimeException();
		 }
		 cb.setStarttime(chosendate.getTime());
		 cb.setTitle(calstuff[0].trim());
		 cb.setDifficulty(Integer.parseInt(calstuff[calstuff.length - 1].trim().split("\\s+")[1]));
		
		return(cb);
	}
	
	/*****************
	 * Looks at the Calendar, Event, and Instance ID
	 * @param blob1
	 * @param blob2
	 * @return
	 */
	public static boolean isSameCalBlob(CalBlob blob1, CalBlob blob2) {
		if(blob1.getCalid() == blob2.getCalid() && blob1.getEventid() == blob2.getEventid() && blob1.getInstanceid() == blob2.getInstanceid()) {
			return true;
		} else {
			return false;
		}
	}
	
	// Finds and returns the position of the most recent quest in the list of quests
	public int findPosRecentDateQuest(ArrayList<CalBlob> datalist) {
		int position = -1;
		long curtime = System.currentTimeMillis();
		
		for(int i=0;i < datalist.size();i++) {
			if(curtime < datalist.get(i).getStarttime()) {				// Event start time > current time
				position = i;
				break;
			}
		}
		
		return(position);
	}
	
	public int genExp(int level) {
		int exp = 0;
		
		Random r = new Random();
		exp=r.nextInt(( (level*2)+1) - level) + level;
		
		return exp;
	}
	
	public int genItem(int level) {
		int item = 0;
		
		return item;
	}
	
	public void increaseExp(Context c, int exp) {
		 Prefs prefs = new Prefs();
		 // Update experience
		 int oldexp = prefs.getMyIntPref(c, "char_exp");
		 int newexp = oldexp + exp;
		 prefs.setMyIntPref(c,newexp, "char_exp");
		 if(Math.floor(newexp / 100) - Math.floor(oldexp / 100) > 0) {		// Broke a 100 mark, go up a level
			 prefs.setMyIntPref(c, prefs.getMyIntPref(c, "char_lvl") + 1, "char_lvl");
			 Toast.makeText(act.getApplicationContext(),"old: " + String.valueOf(oldexp) + " New: " + String.valueOf(newexp),Toast.LENGTH_LONG).show();
		 }
	}
}
